import React, { Component } from 'react';
import {
  Select,
  Form,
  Card,
  Button,
  Row,
  Col,
  Table,
  Divider,
  Tag,
  Input,
  DatePicker,
  Pagination,
  Icon,
  Upload,
} from 'antd';
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
import BaseComponent from '@/components/BaseComponent';
import { connect } from 'dva';
import moment from 'moment';
import ExamineButton from './ExamineButton/index';
import ImgFolderUpload from './ImgFolderUpload';
import ExcelUpload from './ExcelUpload';

@connect(({ user }) => ({
  // data: risk.riskData,
  currentUser: user.currentUser,
}))
export default class index extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      expand: false,
      data: [],
      total: 0,
      ids: [],
      current: 0,
      form: {},
      provinceIdData: [],
      city_codeData: [],
      region_codeData: [],
    };
  }
  city_codeChange = value => {
    const str = value ? this.state.city_codeData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          city_code: value,
          cityName: name,
        },
      }),
      () => {
        this.getCity({ level: 3, parentCode: value });
      }
    );
  };

  onSelectChange = selectedRowKeys => {
    this.setState({ ids: selectedRowKeys });
  };

  region_codeChange = value => {
    const str = value ? this.state.region_codeData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          region_code: value,
          districtName: name,
        },
      }),
      () => {}
    );
  };
  org_nameChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        org_name: value,
      },
    }));
  };
  user_nameChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        user_name: value,
      },
    }));
  };
  id_cardChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        id_card: value,
      },
    }));
  };

  componentDidMount() {
    this.getDataByPage({});
    this.getCity({ level: 2, parentCode: '34' });
  }
  //查询省
  getCity = param => {
    this.execHttp('plannedFollowUp/getCity', { ...param }).then(resp => {
      if (resp) {
        if (param.level == 1) {
          this.setState({
            provinceIdData: resp.data,
          });
        } else if (param.level == 2) {
          this.setState({
            city_codeData: resp.data,
          });
        } else if (param.level == 3) {
          this.setState({
            region_codeData: resp.data,
          });
        }
      }
    });
  };

  //分页切换
  onChangePagination = (page, pageSize) => {
    this.getDataByPage({
      user: this.props.currentUser.id,
      currentPage: page,
      pageSize: pageSize,
      ...this.state.form,
    });
  };
  onShowSizeChange = (current, pageSize) => {
    if (current === 0) {
      current = 1;
    }
    this.getDataByPage({
      user: this.props.currentUser.id,
      currentPage: current,
      pageSize: pageSize,
      ...this.state.form,
    });
  };
  //图片文件夹导入

  imgFolderImport = () => {};

  // 导出
  dataExport = () => {
    const ids = this.state.ids.join('|');

    const hide = this.loadingMessage('正在导出数据，请稍后...');

    this.execHttp('qrCode/exportSelfTestTable', {
      user: this.props.currentUser.id,
      ids: ids,
      ...this.state.form,
    })
      .then(res => {
        hide();
        saveAs(res, '风险因素表导出' + '.xlsx');
      })
      .catch(err => {
        hide();
      });
  };

  //分页
  getDataByPage = params => {
    this.execHttp('qrCode/listAllData', {
      user: this.props.currentUser.id,
      currentPage: 1,
      pageSize: 10,
      ...params,
    }).then(resp => {
      if (resp.success) {
        this.setState({
          data: resp.data.list,
          total: resp.data.pagination.total,
          current: resp.data.pagination.current,
        });
      }
    });
  };

  //查询
  searchClick = () => {
    this.getDataByPage(this.state.form);
  };

  //重置
  resetClick = () => {
    this.setState(
      () => ({
        form: {},
      }),
      () => {
        this.getDataByPage(this.state.form);
      }
    );
  };
  //展开与否状态切换
  handleToggle = () => {
    const { expand } = this.state;
    this.setState({ expand: !expand });
  };

  render() {
    const columns = [
      {
        title: '身份证',
        dataIndex: 'id_card',
        key: 'id_card',
      },
      {
        title: '城市',
        dataIndex: 'city_name',
        key: 'city_name',
      },
      {
        title: '区县',
        dataIndex: 'region_name',
        key: 'region_name',
      },
      {
        title: '姓名',
        dataIndex: 'user_name',
        key: 'user_name',
      },
      {
        title: '机构名称',
        dataIndex: 'org_name',
        key: 'org_name',
      },
      {
        title: '是否高危',
        dataIndex: 'high_risk',
        key: 'high_risk',
        render: val => <span style={{ color: val == 1 ? 'red' : '' }}>{val ? '是' : '否'}</span>,
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <div>
            <ExamineButton record={record}></ExamineButton>
          </div>
        ),
      },
    ];

    const { data, total, current } = this.state;
    const rowSelection = {
      selectedRowKeys: this.state.ids, // 同步选中的行数据
      onChange: this.onSelectChange,
    };

    return (
      <div>
        <Card size="small" style={{ width: '100%' }} bordered={true} title={'风险因素'}>
          <Form layout="horizontal">
            <Row gutter={16}>
              <Col span={5}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.city_code}
                    onChange={this.city_codeChange}
                    placeholder="请选择所属城市"
                  >
                    {this.state.city_codeData.map(item => (
                      <Select.Option key={item.code}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={5}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.region_code}
                    onChange={this.region_codeChange}
                    placeholder="请选择所属区/县"
                  >
                    {this.state.region_codeData.map(item => (
                      <Select.Option key={item.code}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={5}>
                <Form.Item>
                  <Input
                    placeholder="机构名称"
                    value={this.state.form.org_name}
                    onChange={this.org_nameChange}
                  />
                </Form.Item>
              </Col>
              <Col
                span={9}
                style={{ textAlign: 'center', display: 'flex', justifyContent: 'space-around' }}
              >
                <Button type="primary" onClick={this.searchClick}>
                  查询
                </Button>
                <Button onClick={this.resetClick}>重置</Button>
                <Button onClick={this.dataExport}>导出</Button>
                <ImgFolderUpload />

                <ExcelUpload />
                <Row>
                  <a style={{ fontSize: 12 }} onClick={this.handleToggle}>
                    {this.state.expand ? '折叠' : '展开'}
                    <Icon type={this.state.expand ? 'up' : 'down'} />
                  </a>
                </Row>
              </Col>
            </Row>

            <Row gutter={16} style={{ display: this.state.expand ? 'block' : 'none' }}>
              <Col span={5}>
                <Form.Item>
                  <Input
                    placeholder="请输入姓名"
                    value={this.state.form.user_name}
                    onChange={this.user_nameChange}
                  />
                </Form.Item>
              </Col>
              <Col span={5}>
                <Form.Item>
                  <Input
                    placeholder="请输入身份证号"
                    value={this.state.form.id_card}
                    onChange={this.id_cardChange}
                  />
                </Form.Item>
              </Col>
              {/* <Col span={6}>
                                <Form.Item >
                                    <RangePicker placeholder="请选择创建时间" />  createTimeStart   createTimeEnd
                                </Form.Item>
                            </Col> */}
            </Row>
          </Form>
          <Table
            columns={columns}
            dataSource={data}
            rowKey="id"
            pagination={false}
            size="small"
            rowSelection={rowSelection}
            style={{ marginTop: '20px' }}
          />
          <div
            style={{
              marginTop: '20px',
              display: 'flex',
              flexDirection: 'row-reverse',
            }}
          >
            <Pagination
              showSizeChanger={true}
              showQuickJumper
              onChange={this.onChangePagination}
              onShowSizeChange={this.onShowSizeChange}
              defaultCurrent={1}
              current={current}
              total={total}
              showTotal={total => `总共 ${total} 条`}
            />
          </div>
        </Card>
      </div>
    );
  }
}
